﻿using System.Collections.Concurrent;
using System.Threading;

namespace Als.Utils.Task
{
    /// <summary>
    /// 队列
    /// </summary>
    public  class QueueManager
    {
        private static readonly ConcurrentDictionary<string, object> DicPool = new ConcurrentDictionary<string, object>();
        /// <summary>
        /// 睡眠时间（毫秒）
        /// </summary>
        private const int SleepNumber = 1;

        /// <summary>
        /// 加入队列
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Join(string key)
        {
            return Join(key, "");
        }
        /// <summary>
        /// 加入队列。
        /// </summary>
        /// <param name="key">资源Key</param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object Join(string key, object obj)
        {
            var failCount = -1;
            Start:
            //抢资源
            if (TryGet(key, obj)) return obj;
            failCount++;
            //如果重试次数超过了N秒。（1000=1秒）
            if (failCount > 5000)
            {
                return null;
            }
            goto Start;
        }
        /// <summary>
        /// 抢资源
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static bool TryGet(string key, object obj)
        {
            if (!DicPool.Keys.Contains(key)) return DicPool.TryAdd(key, obj);
            Thread.Sleep(SleepNumber);
            return false;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="key"></param>
        public static void Free(string key)
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                DicPool.TryRemove(key, out _);
            }
        }

    }
}
